package com.example.q_kang.hhh.setting;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.example.q_kang.hhh.R;
import com.example.q_kang.hhh.home.MacIntegralDetailActivity;
import com.example.q_kang.hhh.login.LoginActivity;
import com.example.q_kang.hhh.main.MainActivity;
import com.example.q_kang.hhh.util.LanguageUtil;
import com.example.q_kang.hhh.util.TipUtil;
import com.example.q_kang.hhh.view.SelectPictureDialog;
import com.hjq.toast.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener;
import com.sskj.base.AppManager;
import com.sskj.base.AppUpDateFragment;
import com.sskj.base.MVPFragment;
import com.sskj.base.api.Constant;
import com.sskj.base.api.SpConfig;
import com.sskj.base.base.App;
import com.sskj.base.bean.UpdataBean;
import com.sskj.base.bean.UserData;
import com.sskj.base.utils.APKVersionCodeUtils;
import com.sskj.base.utils.ClickUtil;
import com.sskj.base.utils.ImageUtil;
import com.sskj.base.utils.SPUtils;

import java.io.File;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import sskj.lee.appupdatelibrary.BaseUpdateDialogFragment;
import sskj.lee.appupdatelibrary.BaseVersion;

import static android.app.Activity.RESULT_OK;

/**
 * @author Hey
 * Create at  2019/04/09
 */
public class SettingFragment extends MVPFragment<SettingPresenter> {
    @BindView(R.id.iv_header)
    ImageView ivHeader;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.tv_name_a)
    TextView tvNameA;
    @BindView(R.id.tv_bank)
    TextView tvBank;
    @BindView(R.id.tv_alipay)
    TextView tvAlipay;
    @BindView(R.id.tv_wechat)
    TextView tvWechat;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_name_c)
    TextView tvNameC;
    @BindView(R.id.tv_bank_c)
    TextView tvBankC;
    @BindView(R.id.tv_alipay_c)
    TextView tvAlipayC;
    @BindView(R.id.tv_wechat_c)
    TextView tvWechatC;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.tv_login_pwd_c)
    TextView tvLoginPwdC;
    @BindView(R.id.tv_pwd_c)
    TextView tvPwdC;
    @BindView(R.id.tv_feedback_c)
    TextView tvFeedbackC;
    @BindView(R.id.tv_version_c)
    TextView tvVersionC;
    @BindView(R.id.tv_language_c)
    TextView tvLanguageC;
    @BindView(R.id.btn_logout)
    Button btnLogout;
    @BindView(R.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    private String mImagePath;
    private SelectPictureDialog selectPictureDialog;
    private UserData.UserinfoBean userinfoBean;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_setting;
    }

    @Override
    public SettingPresenter getPresenter() {
        return new SettingPresenter();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mPresenter.getUserData(null);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.getUserData(null);
    }

    @Override
    public void initView() {
        ClickUtil.click(300, tvNameC, view -> {
            if (userinfoBean != null) {
                UserInfoActivity.start(getActivity(),
                        userinfoBean.getUsername(),
                        userinfoBean.getNickname(),
                        userinfoBean.getPd_note());
            }
        });
        ClickUtil.click(300, tvBankC, view -> BindingBankActivity.start(getActivity()));
        ClickUtil.click(300, tvAlipayC, view -> {
            BindingAlipayActivity.start(getActivity());
            if (userinfoBean != null && TextUtils.isEmpty(userinfoBean.getZfb_username())) {
            }
        });
        ClickUtil.click(300, tvWechatC, view -> {
            BindingWechatActivity.start(getActivity());
            if (userinfoBean != null && TextUtils.isEmpty(userinfoBean.getWx_username())) {
            }
        });
        ClickUtil.click(300, tvOrder, view -> OrderPeizhiActivity.start(getActivity()));
        ClickUtil.click(300, tvLoginPwdC, view -> SetLoginPwdActivity.start(getActivity()));
        ClickUtil.click(300, tvPwdC, view -> SetDealPwdActivity.start(getActivity()));
        ClickUtil.click(300, tvVersionC, view -> {
            mPresenter.updata(APKVersionCodeUtils.getVerName(getActivity()));
        });
        ClickUtil.click(300, tvFeedbackC, view -> FeedBackActivity.start(getActivity()));
        ClickUtil.click(300, btnLogout, view -> {
            AppManager.getInstance().finishAll();
            SPUtils.put(App.INSTANCE, SpConfig.LOGIN, "0");
            LoginActivity.start(getActivity());
        });
        ClickUtil.click(300, ivHeader, view -> selectPic());
        ClickUtil.click(300, tvLanguageC, view -> {

            TipUtil.getTip(getActivity(), App.INSTANCE.getString(R.string.strGoogleSettingActivity202), new TipUtil.OnTipSure() {
                @Override
                public void onSure() {
                    if ("zh".equals(App.getLANGUAGE())) {
                        SPUtils.put(App.INSTANCE, Constant.LANGUAGE, "en", "english");
                        setLocale(Locale.ENGLISH);
                    } else if ("en".equals(App.getLANGUAGE())) {
                        SPUtils.put(App.INSTANCE, Constant.LANGUAGE, "zh", "chinese");
                        setLocale(Locale.SIMPLIFIED_CHINESE);
                    }
                    AppManager.getInstance().finishAll();
                    MainActivity.start(App.INSTANCE);
                }
            }).show();
        });
    }

    @Override
    public void initData() {
        coolRefreshView.addOnPullListener(new SimpleOnPullListener() {
            @Override
            public void onRefreshing(CoolRefreshView refreshView) {
                mPresenter.getUserData(coolRefreshView);
            }
        });
        mPresenter.getUserData(null);
        tvVersion.setText("V" + APKVersionCodeUtils.getVerName(getActivity()));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 图片、视频、音频选择结果回调
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            mImagePath = TextUtils.isEmpty(selectList.get(0).getCompressPath()) ? selectList.get(0).getPath() : selectList.get(0).getCompressPath();

            mPresenter.uploadImg(new File(mImagePath));
        }
    }

    public void selectPic() {
        if (selectPictureDialog == null) {
            selectPictureDialog = new SelectPictureDialog(getActivity());
        }
        selectPictureDialog.setOnSelectListener(new SelectPictureDialog.SelectListener() {
            @Override
            public void selectByAlbum() {
                PictureSelector.create(SettingFragment.this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(1)
                        .compress(true)
                        .minimumCompressSize(100)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void selectByPhoto() {
                PictureSelector.create(SettingFragment.this)
                        .openCamera(PictureMimeType.ofImage())
                        .maxSelectNum(1)
                        .compress(true)
                        .minimumCompressSize(100)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });
        selectPictureDialog.show();
    }

    public static SettingFragment newInstance() {
        SettingFragment fragment = new SettingFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void uploadSuccess(String data) {
        ImageUtil.setCircleImage(App.INSTANCE, data, ivHeader);
        SPUtils.put(App.INSTANCE, SpConfig.Head, data);
    }

    public void getUserSuccess(UserData.UserinfoBean data) {
        this.userinfoBean = data;
        ImageUtil.setCircleImage(App.INSTANCE, data.getHead(), ivHeader);
        tvName.setText(TextUtils.isEmpty(data.getUsername()) ? App.INSTANCE.getString(R.string.appJavaSettingFragment1) : data.getUsername());
        tvMobile.setText(data.getMobile());
        tvNameA.setText(data.getNickname());
        tvAlipay.setText(TextUtils.isEmpty(data.getZfb_username()) ? App.INSTANCE.getString(R.string.appJavaSettingFragment2) : App.INSTANCE.getString(R.string.appJavaSettingFragment3));
        tvWechat.setText(TextUtils.isEmpty(data.getWx_username()) ? App.INSTANCE.getString(R.string.appJavaSettingFragment2) : App.INSTANCE.getString(R.string.appJavaSettingFragment3));
        tvBank.setText(data.getBankNum());
        if (!TextUtils.isEmpty(data.getZfb_username())) {
            SPUtils.put(App.INSTANCE, SpConfig.ALIPAY, "1");
        }
        if (!TextUtils.isEmpty(data.getWx_username())) {
            SPUtils.put(App.INSTANCE, SpConfig.WECHAT, "1");
        }
        if (!TextUtils.isEmpty(data.getBankNum()) && !data.getBankNum().equals("0")) {
            if (data.getBankNum().equals("0")) {
                SPUtils.put(App.INSTANCE, SpConfig.BANK, "0");
            }
            if (!data.getBankNum().equals("0")) {
                SPUtils.put(App.INSTANCE, SpConfig.BANK, "1");
            }
        }
    }

    public void setLocale(Locale myLocale) {
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);
        LanguageUtil.saveLanguageSetting(App.INSTANCE, myLocale);
    }

    public void needUpdata(UpdataBean updataBean) {

        if (updataBean == null) {
            return;
        }
//        if (updataBean.getUptype().equals("2")) {
//            updataBean.isMustUp();
//        }
        String verName = APKVersionCodeUtils.getVerName(getActivity());
        updataBean.setViewStyle(BaseVersion.NOTIFYCATION_STYLE);
        if (APKVersionCodeUtils.compareVersion(updataBean.getVersion(), verName) == 1) {
            android.app.FragmentTransaction fragmentTransaction = getActivity().getFragmentManager().beginTransaction();
            AppUpDateFragment appUpDateFragment = new AppUpDateFragment();//自定义UI
            Bundle bundle = new Bundle();
            bundle.putSerializable(BaseUpdateDialogFragment.INTENT_KEY, updataBean);
            appUpDateFragment.setArguments(bundle);
            fragmentTransaction.add(appUpDateFragment, "updateUI");
            fragmentTransaction.commitAllowingStateLoss();
        } else {
            ToastUtils.show(App.INSTANCE.getString(R.string.newest_version));
        }


    }
}
